<template>
  <div class="table-search-page">
    <div class="quote-price" v-if="showQuotePrice">
      <quote-price @openBillSuccess="openBillSuccess" @goBack="showQuotePrice=false" ref="quotePrice" :row_record="current_row_record" />
    </div>
    <div v-show="!showQuotePrice">
      <div class="g-tabs-wrapper">
        <a-tabs  :activeKey="currentActiveKey" @change="changeTabs" type="line" >
          <a-tab-pane :key="1">
              <span slot="tab">
                <a-badge :count="badgeCount">等待咨询</a-badge>
              </span>
          </a-tab-pane>
          <a-tab-pane :key="2" tab="咨询中" ></a-tab-pane>
          <a-tab-pane :key="3" tab="咨询完成"></a-tab-pane>
        </a-tabs>
      </div>
      <a-card class="g-mt-10" :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline" :form="form" :selfUpdate="true">
            <a-row :gutter="12">
              <a-col :md="12" :lg="6" :sm="12" style="padding: 0 4px;">
                <a-form-item label="咨询时间">
                  <a-range-picker allow-clear v-decorator="['time']" style="width: 100%;">
                    <a-icon slot="suffixIcon" type="calendar" />
                  </a-range-picker>
                </a-form-item>
              </a-col>
              <a-col :md="12" :lg="5" :sm="12" style="padding: 0 4px;">
                <a-form-item label="客户卡号">
                  <a-input @change="clearSpace"  v-decorator="['cardNo']" allow-clear placeholder="客户卡号"/>
                </a-form-item>
              </a-col>
              <a-col :md="12" :lg="5" :sm="12" style="padding: 0 4px;">
                <a-form-item label="联系号码">
                  <a-input @change="clearSpace" v-decorator="['mobile']" allow-clear placeholder="联系号码"/>
                </a-form-item>
              </a-col>
              <a-col :md="12" :lg="4" :sm="12" style="padding: 0 4px;">
                <a-form-item label="客户姓名">
                  <a-input @change="clearSpace" v-decorator="['name']" style="width: 100%" allow-clear placeholder="姓名"/>
                </a-form-item>
              </a-col>

              <a-col :md="2" :lg="4" :sm="12">
                <div class="table-page-search-submitButtons g-flex" style="margin-bottom: 4px;">
                  <a-icon :type="advanced ? 'up' : 'down'" @click="advanced=!advanced" style="margin-right: 15px;" />
                  <a-button type="primary" @click="clickSearch">查询</a-button>
                  <a-button style="margin-left: 8px" @click="clickReset">重置</a-button>
                </div>
              </a-col>
            </a-row>
            <a-row :gutter="12" v-show="advanced">
              <a-col :md="12" :lg="6" :sm="12" style="padding: 0 4px;">
                <a-form-item label="开发人员">
                  <a-select
                    @search="select_search_developer"
                    :showSearch="true"
                    option-filter-prop="children"
                    allow-clear
                    option-label-prop="label"
                    style="width: 100%"
                    v-decorator="['developer']"
                    placeholder="选择，搜索" >
                    <a-select-option v-for="item in developerUser.userList" :key="item.id" :label="item.name" :value="item.id" >{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :lg="5" :sm="12" style="padding: 0 4px;">
                <a-form-item label="所属咨询">
                  <a-select
                    @search="select_search_consultMan"
                    :showSearch="true"
                    option-filter-prop="children"
                    allow-clear
                    option-label-prop="label"
                    style="width: 100%"
                    v-decorator="['consultMan']"
                    placeholder="选择，搜索" >
                    <a-select-option v-for="item in allHisUser.userList" :key="item.id" :label="item.name" :value="item.id" >{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :lg="5" :sm="12" style="padding: 0 4px;">
                <a-form-item label="客户等级">
                  <a-select
                    allow-clear
                    option-label-prop="label"
                    style="width: 100%"
                    v-decorator="['customerLevel']"
                    placeholder="客户等级" >
                    <a-select-option v-for="item in customerLevel" :key="item.id" :label="item.name" :value="item.id" >{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :lg="4" :sm="12" style="padding: 0 4px;">
                <a-form-item label="客户状态">
                  <a-select
                    allow-clear
                    option-label-prop="label"
                    style="width: 100%"
                    v-decorator="['customerState']"
                    placeholder="状态" >
                    <a-select-option v-for="item in customerState" :key="item.id" :label="item.name" :value="item.id" >{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-card>
      <a-card :bordered="false">
        <super-table
          :expandedRowKeys="expandedRowKeys"
          @expandedRowsChange="expandedRowsChange"
          :pageSize="10"
          :expandIcon="expandIcon"
          :scroll="{ x: 1300}"
          ref="table"
          ls_props_columns="customerReturnList"
          :rowKey="(record,index)=> record.tbConsultSchemeId?record.tbConsultSchemeId:index"
          :columns="columns"
          :data="loadData"
        >
          <!--序号-->
          <template slot="index" slot-scope="text,record,index">
            <span>{{(queryParam.pageNum-1)*pagination.pageSize+(index+1)}}</span>
          </template>
          <!--客户卡号-->
          <template slot="cardNo" slot-scope="text,record">
            <div class="g-flex g-y-center">
              <a class="g-f-14"  @click="toDetails(text, record)">{{ text }}</a>
              <a-tooltip placement="top">
                <template slot="title"> 复制 </template>
                <a-icon type="copy" @click="ConCopy(text)" theme="twoTone" two-tone-color="#3399ff" style="margin-left: 10px;cursor: pointer;" />
              </a-tooltip>
            </div>
          </template>
          <!--咨询项目-->
          <template slot="sqdata" slot-scope="sqdata" >
            <div v-for="(item,index) in sqdata" :key="index">
              <a-tag v-if="item!=''" style="margin-right: 3px;display: inline-block;" :color="tagColor(index)"  >{{ item }}</a-tag>
              <div v-else>-</div>
            </div>
          </template>
          <!--成交状态-->
          <template slot="chargeState" slot-scope="text">
            <span style="color: #3399FF" v-if="text==1"><a-badge color="#3399FF" />已成交</span>
            <span style="color: #FF1F1F" v-if="text==0"><a-badge color="#FF1F1F" />未成交</span>
          </template>

          <!--等待时间-->
          <template slot="intervalTime" slot-scope="text">{{text}}</template>
          <a-table
            size="small"
            slot="expandedRowRender"
            slot-scope="text"
            :columns="innerColumns"
            :data-source="text.schemeList"
            :rowKey="(record)=> record.tbConsultSchemeId"
            :pagination="false"
          >
            <!--序号-->
            <template slot="index" slot-scope="text,record,index">{{(index+1)}}</template>
            <!--提交状态-->
            <template slot="isSubmit" slot-scope="text">
              <span style="color: #3399FF" v-if="text==1"><a-badge color="#3399FF" />是</span>
              <span style="color: #FF1F1F" v-if="text==0"><a-badge color="#FF1F1F" />否</span>
            </template>
            <!--交易状态-->
            <template slot="chargeState" slot-scope="text">
              <span style="color: #3399FF" v-if="text==0"><a-badge color="#3399FF" />未收费</span>
              <span style="color: #FF1F1F" v-if="text==1"><a-badge color="#FF1F1F" />未收完</span>
              <span style="color: #FF1F1F" v-if="text==2"><a-badge color="#FF1F1F" />已收费</span>
            </template>
            <!--嵌套子表格-->
            <span slot="action" slot-scope="record" >
                <a-button style="padding:0;" :disabled="record.isSubmit==1" @click="openBill(record)" type="link">开单</a-button>
                <a-button style="padding:0;" @click="openDrawer(record)" type="link">详情</a-button>
                <a-button style="padding:0;" v-if="currentActiveKey!=1"   @click="openQuotePrice(record)" type="link">报价</a-button>
              </span>
          </a-table>
          <template slot="action" slot-scope="record" >
            <div class="g-flex">
              <a-popconfirm v-if="currentActiveKey==1" title="确定接诊吗?" @confirm="() =>clickSceneSave(record)">
                <a-button class="g-bt-pad-0" type="link">接诊</a-button>
              </a-popconfirm>
              <!--          <a-button  v-if="currentActiveKey==1" @click="clickSceneSave(record)" type="link">接诊</a-button>-->
              <a-button class="g-bt-pad-0" v-if="currentActiveKey!=1" @click="clickEdit(record)" type="link">编辑</a-button>
              <a-button class="g-bt-pad-0" v-if="currentActiveKey!=1" :disabled="hasNoSubmit(record)" @click="openQuotePrice(record)" type="link">报价</a-button>
            </div>
          </template>
        </super-table>
      </a-card>
      <!--编辑--弹窗-->
      <edit-scene-form ref="sceneEdit" :row_record="current_row_record"/>
      <!--开单-弹窗-->
      <open-bill-form ref="openBill" :row_record="current_row_record"/>
      <!--项目抽屉--弹窗-->
      <item-drawer ref="itemDrawer" :row_record="current_row_record" />
    </div>


  </div>


</template>

<script>
import { AllHisUser, CustomerLevel, CustomerState } from '@/api/customer/customer'
import { dictTypeListForCode } from '@/api/modular/main/customer/customerTriage'
import {CustomerFeedback} from '@/api/modular/main/customer/customerReturnVisit'
import {SceneConsultationList, sceneSave} from '@/api/modular/main/customer/customerScene'
import {SuperTable, upTime} from '@/components'
import editSceneForm from './editSceneForm'
import openBillForm from '@/views/customer/customerSceneConsultation/openBillForm'
import itemDrawer from '@/views/customer/customerSceneConsultation/itemDrawer'
import quotePrice from '@/views/customer/customerSceneConsultation/quotePrice'
import moment from 'moment'

export default {
  components:{
    SuperTable,
    editSceneForm,
    openBillForm,
    itemDrawer,
    quotePrice,
    upTime
  },
  data() {
    return {
      expandedRowKeys:[],
      showQuotePrice:false,
      loadData: parameter => {
        this.queryParam.pageNum = parameter.pageNum || 1
        this.queryParam.pageSize = parameter.pageSize || 10
        return SceneConsultationList(this.queryParam).then(res => {
          this.loading = false//关闭加载
          if(this.currentActiveKey==1){
            this.badgeCount=parseInt(res.total)
          }
          return res
        }).catch(()=>{
          this.$message.error('请求错误')
          this.loading = false
        })
      },
      badgeCount:0,
      form: this.$form.createForm(this),
      customerState:[],//客户状态
      customerLevel:[],//客户等级
      advanced: false, // 高级搜索 展开/关闭
      // 高级搜索 展开/关闭
      disabled:true, //是否禁用新增按钮
      current_row_record:{},
      columns: [
        { title: '序号', scopedSlots: { customRender: 'index' },width:80},
        { title: '客户卡号', dataIndex: 'card_no', width: 150 ,scopedSlots: { customRender: 'cardNo' }},
        { title: '客户姓名', dataIndex: 'name', width: 100},
        { title: '客户诉求', dataIndex: 'sqdata', scopedSlots: { customRender: 'sqdata' }, width: 130, ellipsis: true },
        { title: '成交状态', dataIndex: 'dealState', scopedSlots: { customRender: 'chargeState'}, width: 100, ellipsis: true },
        { title: '咨询开始时间', dataIndex: 'okdate', width: 150 },
        { title: '等待时间', dataIndex: 'waitingTime', scopedSlots: { customRender: 'intervalTime' }, width: 100, ellipsis: true},
        { title: '咨询内容', dataIndex: 'consultCondition', width:100, ellipsis: true},
        { title: '开发人', dataIndex: 'developer', width: 90 },
        { title: '所属咨询', dataIndex: 'consultMan', width: 90 },
        { title: '当前咨询师', dataIndex: 'nowConsultMan', width: 100, ellipsis: true },
        { title: '未成交原因', dataIndex: 'noDealReason', width: 100, ellipsis: true },
        { title: '操作', scopedSlots: { customRender: 'action' },width: 100 },
      ],
      innerColumns: [
        { title: '序号', scopedSlots: { customRender: 'index' },width:60, ellipsis: true},
        { title: '提交状态', dataIndex: 'isSubmit', scopedSlots: { customRender: 'isSubmit'}, width: 100, ellipsis: true },
        { title: '收费状态', dataIndex: 'chargeState', scopedSlots: { customRender: 'chargeState'},width: 80, ellipsis: true },

        { title: '应付金额', dataIndex: 'totalPayableAmt', width: 80, ellipsis: true},
        { title: '成交金额', dataIndex: 'totalChargeAmt', width:80, ellipsis: true},
        { title: '增值金抵扣', dataIndex: 'totalItemGold', width: 80, ellipsis: true },
        { title: '券抵扣', dataIndex: 'totalItemTicket', width: 80, ellipsis: true },
        { title: '积分抵扣', dataIndex: 'totalItemJf', width: 80, ellipsis: true },
        { title: '已付金额', dataIndex: 'totalPaidAmt', width: 80, ellipsis: true },
        { title: '未付金额', dataIndex: 'totalUnPaidAmt', width: 80, ellipsis: true },

        { title: '收费时间', dataIndex: 'chargeDate', width: 80, ellipsis: true },
        { title: '方案内容', dataIndex: 'schemeContent', width: 100, ellipsis: true },
        { title: '操作', scopedSlots: { customRender: 'action' },width: 120 },
      ],

      data: [],
      pagination: {
        current: 1,//当前页
        pageSize: 10,//当前页数
        total: 0,//总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'],//这里注意只能是字符串，不能是数字
        showTotal: total => `共有 ${total} 条数据`,//分页中显示总的数据
      },
      // 查询参数
      queryParam: {
        pageNum: 1,//第几页
        pageSize: 10,//每页中显示数据的条数
        type:1,
        beginTime:undefined,
        endTime:undefined
      },
      submitQueryParam:{
        consultRecord:{}
      },
      loading: true, //加载状态,
      current_row_index:'',
      customerFeedback:{},
      allHisUser:{}, //回访人对象
      developerUser:{},//所属咨询
      currentActiveKey:1
    }
  },
  activated(){
    this.$refs.table.refresh()
    // this.currentActiveKey=1
    this.changeTabs(1)
  },
  created() {
    this.getBaseFormInfo()
  },
  methods: {
    clearSpace(e){
       e.target.value=e.target.value.replace(/\s+/g,'')
    },
    expandInnerTable(flag,record){
      let current_index
      this.table_arr.forEach((item,index)=>{
        if(item.ID==record.ID) current_index=index
      })
      console.log('current_index',current_index)
      this.$nextTick(() => {
        const fixed_right_element = document.querySelectorAll('.ant-table-fixed-right .ant-table-body-outer .ant-table-fixed .ant-table-tbody .ant-table-row')
        const element =document.getElementsByClassName('ant-table-row')
        const element_offset_height = element[0].offsetHeight
        if(flag){
          const expand_element = document.querySelectorAll('.ant-table-expanded-row')
          console.log('expand_element',expand_element,expand_element.offsetHeight)
          fixed_right_element[current_index].style.height = '156px'
        }else{
          fixed_right_element[current_index].style.height = element_offset_height+'px'
        }
      })
    },
    //开单成功
    openBillSuccess(){
      this.showQuotePrice=false
      this.queryParam.type=3
      this.$refs.table.refresh()
      this.currentActiveKey=3
    },
    checkPattern(str){
      const pattern = new RegExp('[\u4E00-\u9FA5]+')
      if(pattern.test(str)){
        return true
      }
      return false
    },
    //下拉框搜索查找
    select_search_consultMan(value){
      this.form.setFieldsValue({
        consultMan:value
      })
    },
    //下拉框搜索查找
    select_search_developer(value){
      this.form.setFieldsValue({
        developer:value
      })
    },

    moment,
    minutesToSeconds(time){
      return parseInt(time)
    },
    currentRow(record,index){
      return index==this.current_row_index?'currentRowClass':''
    },
    //点击查询-高级搜索
    clickSearch(){
      const form_values = this.form.getFieldsValue()
      const time = form_values.time
      if(time&&time.length>0){
        form_values.beginTime=moment(time[0]).format('YYYY-MM-DD')
        form_values.endTime=moment(time[1]).format('YYYY-MM-DD')
        form_values.time=undefined
      }
      /**下拉框搜索**/
      const tempConsultManFlag = this.checkPattern(form_values.consultMan)
      const tempdeveloperFlag = this.checkPattern(form_values.developer)
      let tempConsultManValue
      let tempdeveloperValue
      if(tempConsultManFlag){
        const obj = this.allHisUser.userList.filter(item=>form_values.consultMan == item.name)[0]
        tempConsultManValue = form_values.consultMan
        form_values.consultMan=obj?obj.id:tempConsultManValue
      }
      if(tempdeveloperFlag){
        const obj = this.allHisUser.userList.filter(item=>form_values.developer == item.name)[0]
        tempdeveloperValue = form_values.developer
        form_values.developer=obj?obj.id:tempdeveloperValue
      }
      this.queryParam=Object.assign(this.queryParam,form_values)
      console.log('查询参数queryParam',this.queryParam)
      this.$refs.table.refresh(true)
      setTimeout(()=>{
        if(tempConsultManFlag){
          this.form.setFieldsValue({
            consultMan:tempConsultManValue
          })
        }
        if(tempdeveloperFlag){
          this.form.setFieldsValue({
            developer:tempdeveloperValue
          })
        }
      },500)
    },
    clickReset(){
      this.form.resetFields()
      this.queryParam={}
      this.queryParam.pageSize=10
      this.queryParam.pageNum=1
      // this.queryParam.beginTime=undefined
      // this.queryParam.endTime=undefined
    },
    /**
     * 点击接诊发送请求
     **/
    clickSceneSave(record){
      console.log('点击接诊',record)
      const obj={
        consultRecord:{
          customerId:record.customerId,
          receiveId:record.receiveId,
          triageId:record.triageId
        }
      }
      sceneSave(obj).then(res=>{
        console.log('接诊结果',res)
        if(res.code==200){
          this.$message.success({
            content:'接诊成功',
            duration:1,
            onClose:()=>{
              this.badgeCount--
              this.queryParam.type = 2
              this.$refs.table.loadData()
              this.currentActiveKey=2
            }
          })
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    /**
     * 存在未提交方案
    * */
    hasNoSubmit(record){
      const schemeList = record.schemeList
      if (!schemeList||schemeList.length<=0) return false
      const hasNoSubmitItem = schemeList.find(item=> {
        return item.isSubmit == 0
      })
      if (!hasNoSubmitItem) return false
      const isSubmit = hasNoSubmitItem.isSubmit
      return isSubmit == 1 ?false:true
    },
    changeTabs(key) {
      this.currentActiveKey=key
      this.queryParam.type = key
      this.$refs.table.loadData()
      this.expandedRowKeys=[]
    },
    tagColor(index){
      return index%2==0?'#2db7f5':'#87d068'
    },
    //点击查看客户详情
    toDetails(text,record){
      this.$router.push({path:'customer_details',query:{
          id:record.customerId,
          card_no:record.card_no,
          customerName:record.name
        }})
    },
    clickAdd(record){
      this.current_row_record=record
      this.$refs.sceneReceice.add()
    },
    clickEdit(record){
      this.current_row_record=record
      this.$refs.sceneEdit.add()
    },
    openBill(record){
      this.current_row_record=record
      this.$refs.openBill.add()
    },
    openDrawer(record){
      this.current_row_record=record
      this.$refs.itemDrawer.show()
    },
    openQuotePrice(record){
      this.showQuotePrice=true
      this.current_row_record=record
      this.$nextTick(()=>{
        this.$refs.quotePrice.show()
      })

    },
    // 表格行点击事件
    clickRow(record, index){
      return {
        on: {
          click:()=>{
            // console.log('点击当前行',record)
            this.disabled=false
            this.current_row_index=index
            this.current_row_record=record
          }
        }
      }
    },
    //获取表单相关接口
    getBaseFormInfo(){
      CustomerFeedback().then(res=>{
        // console.log('回访相关表单接口',res)
        this.customerFeedback=res
      })
      // dictTypeListForCode  AllHisUser  所属咨询
      dictTypeListForCode({code:"XCZXS"}).then((res) => {
        // console.log('全员员工接口',res)
        this.allHisUser = res
      })
      // 开发人员 
      dictTypeListForCode({code:"WLZXS"}).then((res) => {
        // console.log('全员员工接口',res)
        this.developerUser = res
      })
      CustomerLevel().then(res => {
        this.customerLevel = res
      })
      CustomerState().then(res => {
        this.customerState = res
      })
    },
    /**
     * 点击展开行
     * **/
    expandedRowsChange(expandedRows){
      this.expandedRowKeys = expandedRows.slice(-1)
    },
    expandIcon (props) {
      if (props.record.schemeList&&props.record.schemeList.length>0) {
        if (props.expanded) {//有数据-展开时候图标
          return (
            <a style="color: 'black',margin-right:0px" onClick={(e) => {
              e.preventDefault()
              e.stopPropagation()
              props.onExpand(props.record, e)
            }}>
              <a-icon style="font-size:14px;" type="minus-square" />
            </a>
          )
        } else {//有数据-未展开时候图标
          return (
            <a style="color: 'black' ,margin-right:0px" onClick={(e) => {
              e.preventDefault()
              e.stopPropagation()
              props.onExpand(props.record, e)
            }}>
              <a-icon style="font-size:14px;" type="plus-square" />
            </a>
          )
        }
      }
    }
  }

}
</script>

<style lang="less" scoped>

.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
  margin-bottom: 2px;
}
.currentRowClass{
  background: #e6f7ff;
}
/deep/ .ant-badge-count, .ant-badge-dot, .ant-badge .ant-scroll-number-custom-component{
  right: -10px;
}
.quote-price{
  position: relative;
  width: 100%;
  min-height: 700px;
  z-index: 100;
}
</style>